//Demo
layui.use('form', function(){
    var form = layui.form;

    //监听提交
    form.on('submit(formDemo)', function(data){
        layer.msg(JSON.stringify(data.field));
        return false;
    });
});


//添加角色
$(function () {
    $("#add").click(function () {
        var add_tags = layer.open({
            type:1,
            area:['350px','350px'],
            title: "新增标签"
            ,content: $("#add_category"),
            shade: 0,
            btn: ['提交', '重置']
            ,btn1: function(index, layero){//提交按钮
                var name = $("#name").val()
                var description = $("#description").val()
                var alias = $("#alias").val()
                var sort = $("#sort").val()

                if(name == null || name == ""){
                    alert("角色名称不能为空")
                    return false;
                }
                if(description == null || description == ""){
                    alert("角色描述不能为空")
                    return false;
                }
                var formData = {
                    name: name,
                    description: description,
                    alias: alias,
                    sort: sort
                }
                $.ajax({
                    url: '/admin/role/add',
                    method: "post",
                    data: formData,
                    success: (response) => {
                        if (response.code == 0) {
                            alert("创建角色成功")
                            location.reload()
                        } else {
                            alert(response.msg)
                            return false
                        }
                    },
                })
            },
            btn2: function(index, layero){//重置按钮
                $("#name").val("")
                $("#description").val("")
            },
            cancel: function(layero,index){//关闭按钮
                layer.close(add_tags);
            }
        });
    })
})
//批量删除删除角色
$(function(){
    $("#dels").click(function () {
        var ids = [];
        var id_data = layui.table.checkStatus('id').data
        console.log(id_data)
        for (var i = 0; i < id_data.length; i+=1){
            ids.push(id_data[i]['id']);
        }
        if(id_data.length == 0){
            alert("请选择要删除的信息")
        }else{
            layer.confirm('你确认要删除这些角色么', {
                time: 0,
                title: '批量角色',
                btn: ['确认', '取消'],
            }, function (index) {
                $.ajax({
                    url:"/admin/role/delete"
                    ,method : "delete"
                    ,data:{'roleIdArray':ids}
                    ,success: (response)=>{
                        if (response.code == 0){
                            alert("删除成功")
                            location.reload();
                        }else{
                            alert(response.msg)
                        }
                    }
                });
            },function (index) {
                layer.close(index);
            });
        }
    })
})

//查看,修改-弹框
layui.use(['table','tree','laypage'], function(){
    var table = layui.table;
    var tree = layui.tree;
    table.render({
        elem: '#role'
        ,size: 'lg' //开启大尺寸样式
        ,url:'/admin/role/get_list'
        ,id: 'id'
        ,page: true
        ,cols: [[
            {type:'checkbox'},
            // {field: 'id', title: 'id', sort: true, fixed: 'left'}
            ,{field: 'name', title: '角色名称',width:100}
            ,{field: 'description', title: '角色描述',width:100}
            ,{field: 'createTime', title: '创建时间',  sort: true}
            ,{title: "操作", fixed: 'right', align: 'center', toolbar: '#bar'}
        ]]
        ,limit:5
        ,limits:[5,10,20,30]

    });
    //监听工具条
    table.on('tool(role)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
        var id = data.id;
        console.log("进入select")
        if (layEvent == "select") {//查看
            $.ajax({
                url:'/admin/role/get/' + id
                ,method: 'get'
                ,success: (response) => {
                    console.log(response)
                    $("#uname").val(response.data.name);
                    $("#rname").val(response.data.description)
                    $("#ctime").val(response.data.createTime);
                    var user_open = layer.open({
                        type: 1,
                        area: ['400px', '400px'],
                        title: "权限列表"
                        ,content: $("#sel_user")
                        ,shade: 0
                        ,btn: []
                        ,cancel: function (layero, index) {//关闭按钮
                            layer.close(user_open);
                        },
                    })
                }
            });
        }else if(layEvent == "update"){
            $.ajax({
                url:'/admin/role/get/' + id
                ,method: 'get'
                ,success: (response) => {
                    console.log(response)
                    $("#up_uname").val(response.data.name);
                    $("#up_nname").val(response.data.description)
                    var user_open = layer.open({
                        type: 1,
                        area: ['400px', '400px'],
                        title: "权限列表"
                        ,content: $("#update_user")
                        ,shade: 0
                        ,btn: ["修改","取消"]
                        ,btn1:function(index,layero){
                            var name = $("#up_uname").val()
                            var description = $("#up_nname").val()
                            var id = response.data.id
                            var formData = {
                                name:name
                                ,description:description
                                ,id:id
                            }
                            $.ajax({
                                url:"/admin/role/update/"
                                ,method:"put"
                                ,data:formData
                                ,success:(response) => {
                                    console.log(response)
                                    if (response.code == 0) {
                                        alert("修改角色成功")
                                        location.reload()
                                    } else {
                                        alert(response.msg)
                                        return false
                                    }
                                }
                            })
                        }
                        ,cancel: function (layero, index) {//关闭按钮
                            layer.close(user_open);
                        },
                    })
                }
            });
        }else if(layEvent == "update2"){//修改
            $.ajax({
                url:'/admin/role/list_permission/' + id,
                method: 'get',
                success: (response) => {
                    tree.render({
                        elem: '#perm_tree',
                        showCheckbox: true,//显示复选框
                        data: response,
                        id: 'id'
                    })
                    var perm_open = layer.open({
                        type: 1,
                        area: ['400px', '500px'],
                        title: "权限列表"
                        , content: $("#perm_tree"),
                        shade: 0,
                        btn:['提交','重置'],
                        btn1: function (index, layero) {//提交按钮
                            var permissionIdArray = []
                            var obj_list = tree.getChecked('id');
                            var ye = obj_list
                            for(var i = 0; i < ye.length; i += 1){
                                permissionIdArray.push(ye[i].id)
                                var fu = ye[i].children
                                for(var j = 0; j < fu.length; j += 1){
                                    permissionIdArray.push(fu[j].id)
                                    var zi = fu[j].children
                                    for(var k = 0; k < zi.length; k += 1){
                                        permissionIdArray.push(zi[k].id)
                                    }
                                }
                            }

                            console.log(permissionIdArray)
                            $.ajax({
                                url: "/admin/role/update_permission/",
                                method: "put",
                                data: {'roleId': id, permissionArray: permissionIdArray},
                                success: (response) => {
                                    if (response.code == 0) {
                                        alert("更新权限成功")
                                        location.reload()
                                    } else {
                                        alert(response.msg)
                                    }
                                }
                            });
                            return false
                        }
                        ,btn2: function (index, layero) {//重置按钮
                            return false
                        }
                        ,cancel: function (layero, index) {//关闭按钮
                            layer.close(perm_open)
                        }
                    })
                }
            })
        }else if (layEvent == "delete"){
            var ids = [];
            ids.push(id)
            layer.confirm('你确认要删除此角色么', {
                time: 0,
                title: '删除角色',
                btn: ['确认', '取消'],
            }, function (index) {
                $.ajax({
                    url:"/admin/role/delete"
                    ,method : "delete"
                    ,data:{'roleIdArray':ids}
                    ,success: (response)=>{
                        if (response.code == 0){
                            alert("删除成功")
                            location.reload();
                        }else{
                            alert(response.msg)
                        }
                    }
                });
            },function (index) {
                layer.close(index);
            });
        }
    });
});

